# coding=utf-8
from abc import ABCMeta
import tornado.web
import tornado.escape
import json

from CommonLib import CheckJsonKeys, CheckAuth
from database.models.DatabaseCommon import *
from database.models.Normal import Normal
from database.models.OperationSet import OperationSet
import WrapCursor
from database.models.PanelInstruct import PanelInstruct


class GetPanelNormal(tornado.web.RequestHandler):
    __metaclass__ = ABCMeta

    def post(self):
        ojson = None
        r = WrapCursor.WrapCursor()
        try:
            ojson = json.loads(self.request.body)
            CheckJsonKeys(ojson, 'id')
            CheckJsonKeys(ojson, 'username', 'userpass')
            CheckAuth(ojson)
        except Exception as e:
            self.write(r.Error(u'请求数据错误' + str(e)))
            return
        iid = ojson['id']
        s = Session()
        if iid != -1:
            nc = s.query(PanelInstruct).filter_by(id=iid).all()
            if len(nc) is not 1:
                self.write(r.Error(u'动作不存在'))
                return
            ops = nc
        else:
            ops = s.query(PanelInstruct).all()

        ret = dict()
        ret['Code'] = 0
        ret['desc'] = u'成功'
        data = list()
        if ops is not None and len(ops) >= 1:
            for i in ops:
                item = dict()
                item['ControllerID'] = i.ControllerID
                item['id'] = i.id
                item['key'] = i.Key
                item['normalID'] = i.NormalID
                data.append(item)
        ret['data'] = data
        self.write(json.dumps(ret))
        return
